package com.aidex.biz.service.impl;

import com.aidex.biz.domain.JdkyOrder;
import com.aidex.biz.domain.Order;
import com.aidex.biz.mapper.OrderMapper;
import com.aidex.biz.service.JdKuaiyunService;
import com.aidex.biz.service.JdkyOrderService;
import com.aidex.biz.service.OrderService;
import com.aidex.biz.service.QingYangOrderService;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.config.AiDexConfig;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sql.SqlUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersCreateLopResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 订单Service业务层处理
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-07-04
 */
@Service
@Transactional(readOnly = true)
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Order> implements OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private JdKuaiyunService jdKuaiyunService;

    @Autowired
    private JdkyOrderService jdkyOrderService;

    @Autowired
    private QingYangOrderService qingYangOrderService;




    /**
     * 获取单条数据
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public Order get(Order order) {
        Order dto = super.get(order);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 订单id
     * @return 订单
     */
    @Override
    public Order get(String id) {
        Order dto = super.get(id);
        return dto;
    }


    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<Order> findList(Order order) {
        return super.findList(order);
    }

    /**
     * 分页查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Order> findPage(Order order) {
        return super.findPage(order);
    }

    /**
     * 保存订单
     *
     * @param order
     * @return 结果
     */
    @Override
    public boolean save(Order order) {
        return super.save(order);
    }


    /**
     * 删除订单信息
     *
     * @param order
     * @return 结果
     */
    @Override
    public boolean remove(Order order) {
        return super.remove(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteOrderByIds(String[] ids) {
        return mapper.deleteOrderByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int findMaxSort(Order order) {
        return NumberUtils.nextOrder(mapper.findMaxSort(order));
    }


    /**
     * 自定义分页
     *
     * @param order
     * @return
     */
    @Override
    public PageInfo<Order> findPageSelf(Order order) {
        PageDomain page = order.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            page.setReasonable(true);
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.findListSelf(order));
    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateQyOrderDelivery(Order order) {
        return mapper.updateQyOrderDelivery(order);
    }


    @Override
    @Transactional(readOnly = false)
    public Integer updateQyOrderReceive(Order order) {
        return mapper.updateQyOrderReceive(order);
    }

    @Override
    public Integer updateByQinXi(Order order) {
        return mapper.updateByQinXi(order);
    }

    @Override
    public List<Order> findIsNotBillOrder(Order order) {
        return mapper.findIsNotBillOrder(order);
    }

    @Transactional(readOnly = false)
    @Override
    public Integer updateBy7Day() {
        return mapper.updateBy7Day();
    }

    @Transactional(readOnly = false)
    @Override
    public Integer updateBy15Day() {
        return mapper.updateBy15Day();
    }

    @Override
    public Order getByQinYangId(Order order) {
        return mapper.getByQinYangId(order);
    }

    @Override
    @Transactional(readOnly = false)
    public Integer batchUpdateOrderStatus(Map<String, Object> param) {
        return mapper.batchUpdateOrderStatus(param);
    }

    @Override
    @Transactional(readOnly = false)
    public Integer updateOutCount(Order order) {
        return mapper.updateOutCount(order);
    }

    @Override
    @Transactional(readOnly = false)
    public String pushJdKuaiYun(Order order) {
        // 平台订单推送到京东快递
        try{

                EcapV1OrdersCreateLopResponse ecapV1OrdersCreateLopResponse= jdKuaiyunService.sendJdKuaiYuanOrder(order);
                JdkyOrder jdkyOrder=new JdkyOrder();
                jdkyOrder.setOrderId(order.getId());
                if("0".equals(ecapV1OrdersCreateLopResponse.getCode())){
                    order.setDeliveryNo(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
                    jdkyOrder.setOrderCode(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
                    jdkyOrder.setStatus("1");
                    // 修改轻氧运单号
                    JSONObject jsonObject=qingYangOrderService.modifyDeliveryNumber(order);
                    if("200".equals(jsonObject.getString("code"))){
                        jdkyOrder.setStatus("2");
                        jdkyOrder.setRemark("京东快运订单推送成功！(取件)");
                    }else{
                        jdkyOrder.setRemark(jsonObject.toString());
                    }

                }else{
                    jdkyOrder.setStatus("0");
                    jdkyOrder.setRemark(ecapV1OrdersCreateLopResponse.getMsg());

                }
                jdkyOrderService.save(jdkyOrder);
            return order.getDeliveryNo();
        }catch (Exception e){
            log.error("创建京东订单失败",e.getMessage());
            return null;
        }


    }

    @Override
    @Transactional(readOnly = false)
    public String pushJdKuaiYun(Order order,String type) {
        // 平台订单推送到京东快递
        try{
            if(AiDexConfig.getCompanyId().equals(order.getCompanyId())){
                EcapV1OrdersCreateLopResponse ecapV1OrdersCreateLopResponse= jdKuaiyunService.sendJdKuaiYuanOrder(order);
                JdkyOrder jdkyOrder=new JdkyOrder();
                jdkyOrder.setOrderId(order.getId());
                if("0".equals(ecapV1OrdersCreateLopResponse.getCode())){
                    order.setReceiveNo(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
                    jdkyOrder.setOrderCode(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
                    jdkyOrder.setStatus("2");
                    jdkyOrder.setRemark("京东快运订单推送成功！（送件）");
                    // 修改轻氧运单号
                    //JSONObject jsonObject=qingYangOrderService.modifyDeliveryNumber(order);
//                    if("200".equals(jsonObject.getString("code"))){
//                        jdkyOrder.setStatus("2");
//                        jdkyOrder.setRemark("京东快运订单推送成功！（送件）");
//                    }else{
//                        jdkyOrder.setRemark(jsonObject.toString());
//                    }
                }else{
                    jdkyOrder.setStatus("0");
                    jdkyOrder.setRemark(ecapV1OrdersCreateLopResponse.getMsg());
                }
                jdkyOrderService.save(jdkyOrder);
            }
            return order.getReceiveNo();
        }catch (Exception e){
            log.error("创建京东订单失败",e.getMessage());
            return null;
        }


    }


}
